package com.jiazhong.Servlet;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;

/**
 * 基础Servlet类
 * 该类的功能只负责接收客户端的请求（method），然后根据method的值将请求转发到对应的Servlet方法进行处理
 * 约定：method的参数值，必须为某个“Servlet方法”的方法名
 */
public class BaseServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest request,
                           HttpServletResponse response) throws ServletException, IOException {
        try {
            request.setCharacterEncoding("UTF-8");
            //获得客户端的请求，此处只取参数名为method的请求参数
            String methodName = request.getParameter("method");
            if (methodName==null || methodName.trim().equals("")){
                throw new Exception("请求错误，请携带method参数");
            }
            //每个Servlet方法的参数为HttpServletRequest和HttpServletResponse
            //通过方法名和方法类型获得一个method对象
            Method method = this.getClass().getDeclaredMethod(methodName,
                                                      HttpServletRequest.class,
                                                              HttpServletResponse.class);
            //调用method方法
            method.invoke(this,request,response);


        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
